package io.gitee.hchaojie.day07;

import org.junit.Test;

public class TestRecursion {

    @Test
    // 斐波那契数列
    public void testFab() {
        // 1 1 2 3 5 8 13 21 34 55

        for (int i = 0; i < 10; i++) {
            System.out.print(fab(i) + " ");
        }
    }

    // f(0) = 1
    // f(1) = 1
    // f(2) = 2
    // f(3) = 3
    // ....
    // f(n) = f(n-1) + f(n-2)
    public int fab(int index) {
        if (index == 0 || index == 1) {     // 递归的终止条件
            return 1;
        } else {
            return fab(index - 1) + fab(index - 2); // 递归公式
        }
    }

    @Test
    public void testSum() {
        System.out.println(sum(100));
    }

    // sum(1)  = 1              1
    // sum(2)  = 3              1 + 2
    // sum(3)  = sum(2) + 3     1 + 2 + 3
    // sum(n) = sum(n-1) + n
    public int sum(int num) {
        if (num == 1) {
            return 1;
        } else {
            return sum(num - 1) + num;
        }
    }
}
